#pragma once
#include "DeviceMessageBuilder.h"
#include <stdexcept>
#include <memory>
#include <iostream>
#include <iomanip>

namespace DeviceCommons {

    // V2 Protocol Parser - Simplified version supporting only V2 protocol
    // Compatible with C# version V2 protocol implementation
    class DeviceMessageParserV2 {
    public:
        // Protocol version constants
        static constexpr uint8_t PROTOCOL_VERSION_V2 = 0x02;
        
        struct ParsedMessage {
            uint8_t protocolHeader[2];  // 0xC0, 0xBF
            uint8_t version;            // Protocol version (V2 = 0x02)
            uint8_t mark;               // Mark byte containing flags
            
            // Mark byte parsed fields
            TimeStampFormat timeStampFormat;
            HeaderValueType headerValueType;
            Reserve1 reserve1;
            Reserve2 reserve2;
            CRCType crcType;
            
            DeviceInfo mainDevice;
            std::vector<DeviceInfo> childDevices;
            
            // CRC verification info
            bool crcValid;
            uint16_t calculatedCRC;
            uint16_t messageCRC;
        };

        // Parse from hex string
        static ParsedMessage parseFromHex(const std::string& hexString);

        // Parse from byte array - V2 protocol only
        static ParsedMessage parseFromBytes(const std::vector<uint8_t>& data);

    private:
        // Parse Mark byte flags
        static void parseMarkByte(uint8_t mark, ParsedMessage& result);

        // V2 protocol parsing: header -> devices (main device + child devices)
        static void parseV2Protocol(const std::vector<uint8_t>& data, size_t offset, ParsedMessage& result);

        // Parse device information
        static DeviceInfo parseDeviceInfo(const std::vector<uint8_t>& data, size_t& offset);

        // Parse reading information
        static Reading parseReading(const std::vector<uint8_t>& data, size_t& offset);

        // Parse state information
        static State parseState(const std::vector<uint8_t>& data, size_t& offset);

        // Verify CRC
        static void verifyCRC(const std::vector<uint8_t>& data, size_t offset, ParsedMessage& result);
    };

    // Helper Functions (declared, implemented in source file)
    std::vector<uint8_t> hexToBytes_impl(const std::string& hex);
    uint16_t crc16_parser_impl(const std::vector<uint8_t>& data);
    
    // Print parsed message details
    void printParsedMessage(const DeviceMessageParserV2::ParsedMessage& msg);

} // namespace DeviceCommons